package com.itheima.algorithm.hashtable;

import java.util.*;

/**
 * @author: TylerZhong
 * @description:
 */
public class E08Leetcode819 {
    /**
     * 1. 将 paragraph 截取为一个个单词
     * 2. 将单词加入 map 集合，单词本身作为 key, 出现次数作为 value, 避免禁用词加入
     * 3. 在 map 集合中找到 value 最大的，返回它对应的 key 即可
     * @param paragraph
     * @param banned
     * @return
     */
    public String mostCommonWord1(String paragraph, String[] banned) {
        Set<String> set = Set.of(banned);
        String[] split = paragraph.toLowerCase().split("[^A-Za-z]+");
        HashMap<String, Integer> map = new HashMap<>();
        for (String s : split) {
            if (!set.contains(s)) {
                map.compute(s, (k, v) -> v == null ? 1 : v + 1);
            }

//            Integer value = map.get(s);
//            if (value == null) {
//                value = 0;
//            }
//            map.put(s, value + 1);
        }
//        System.out.println(map);
        Optional<Map.Entry<String, Integer>> optional = map.entrySet().stream().max(Map.Entry.comparingByValue());
        return optional.map(Map.Entry::getKey).orElse(null);
    }
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> set = Set.of(banned);
        HashMap<String, Integer> map = new HashMap<>();
        char[] chars = paragraph.toLowerCase().toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chars) {
            if (ch >= 'a' && ch <= 'z') {
                sb.append(ch);
            } else {
                String key = sb.toString();
                if (!set.contains(key)) {
                    if (!sb.isEmpty()) {
                        map.compute(key, (k, v) -> v == null ? 1 : v + 1);
                    }
                }
//                sb = new StringBuilder();
                sb.setLength(0);
            }
        }
        if (!sb.isEmpty()) {
            String key = sb.toString();
            if (!set.contains(key)) {
                map.compute(key, (k, v) -> v == null ? 1 : v + 1);
            }
        }
        System.out.println(map);
        int max = 0;
        String maxKey = null;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Integer value = entry.getValue();
            if (max < value) {
                max = value;
                maxKey = entry.getKey();
            }
        }
        return maxKey;
    }

    public static void main(String[] args) {
        E08Leetcode819 e08Leetcode819 = new E08Leetcode819();
        String key = e08Leetcode819.mostCommonWord("Bob. hIt, baLl", new String[]{"bob", "hit"});
        System.out.println(key); // ball
    }
}
